package 原子类;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * @program: algorithm
 * @description:
 * @author: 陈恩涛
 * @create: 2022-08-29 11:33
 **/
public class AtomicReferenceFieldUpdaterDemo {

    public static void main(String[] args) {
        final MyVar myVar = new MyVar();

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                myVar.init();
            },String.valueOf(i)).start();
        }
    }
}

class MyVar{

    public volatile Boolean inited = Boolean.FALSE;

    private AtomicReferenceFieldUpdater<MyVar, Boolean> referenceFieldUpdater = AtomicReferenceFieldUpdater.newUpdater(MyVar.class, Boolean.class, "inited");

    public void init() {
        if (referenceFieldUpdater.compareAndSet(this, Boolean.FALSE, Boolean.TRUE)) {
            System.out.println(Thread.currentThread().getName() + "\t" + "------start init, need 2 seconds");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + "------init is over");
        } else {
            System.out.println(Thread.currentThread().getName() + "\t" + "已经有其他前程进行了初始化工作！");
        }
    }
}
